package com.zengqingfa.examples.mybatisplus.rest;

import cn.hutool.http.server.HttpServerResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.zengqingfa.examples.mybatisplus.annotation.LogHistory;
import com.zengqingfa.examples.mybatisplus.common.OperateType;
import com.zengqingfa.examples.mybatisplus.context.UserInfoContext;
import com.zengqingfa.examples.mybatisplus.dto.UserQueryVo;
import com.zengqingfa.examples.mybatisplus.dto.UserVo;
import com.zengqingfa.examples.mybatisplus.entity.User;
import com.zengqingfa.examples.mybatisplus.excel.ExcelListener;
import com.zengqingfa.examples.mybatisplus.excel.ExcelUtil;
import com.zengqingfa.examples.mybatisplus.excel.ExportUserModel;
import com.zengqingfa.examples.mybatisplus.excel.MonthSheetWriteHandler;
import com.zengqingfa.examples.mybatisplus.response.Result;
import com.zengqingfa.examples.mybatisplus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @fileName: UserController
 * @author: zengqf3
 * @date: 2021-3-2 14:59
 * @description:
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    private AtomicInteger atomicInteger=new AtomicInteger(1);

    @PostMapping("/create")
    @Transactional(rollbackFor = Exception.class)
//    @LogHistory(operateType = OperateType.ADD)
    public Result create(@RequestBody User user) {
//        user.setCreateUserCode(UserInfoContext.getUser());
//        user.setUpdateUserCode(UserInfoContext.getUser());


//        String userCode = UserInfoContext.getUser();
//        threadPoolExecutor.submit(()->{
//            UserInfoContext.setUser(userCode);
//            try {
//                boolean save = userService.save(user);
//            } finally {
//                UserInfoContext.clear();
//            }
//        });
        user.setAge(atomicInteger.getAndIncrement());
        user.setName(user.getName()+"-"+atomicInteger.get());
        user.setEmail(user.getEmail()+"-"+atomicInteger.get());
        threadPoolExecutor.submit(()->{
            //UserInfoContext.getUser(); 存在值
            try {
                boolean save = userService.save(user);
            } finally {
                UserInfoContext.clear();
            }
        });
        return Result.success(true);
    }

    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
//    @LogHistory(operateType = OperateType.UPDATE)
    public Result update(@RequestBody User user) {
        boolean update = userService.updateById(user);
        return Result.success(update);
    }

    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
//    @LogHistory(operateType = OperateType.DELETE)
    public Result delete(@RequestBody User user) {
        boolean remove = userService.removeById(user.getId());
        return Result.success(remove);
    }

    @PostMapping("/selectUserPage1")
    public Result selectUserPage1(@RequestBody User user) {
        log.info("user:{}", JSONObject.toJSONString(user));
        log.error("user:{}", JSONObject.toJSONString(user));
        IPage<User> page = userService.selectUserPage1(user);
        return Result.success(page);
    }



    @GetMapping("/selectUserPage2")
    public Result selectUserPage2(@RequestBody User user) {
        log.info("user:{}", JSONObject.toJSONString(user));
        log.error("user:{}", JSONObject.toJSONString(user));
        IPage<User> page = userService.selectUserPage2(user);
        return Result.success(page);
    }

    @GetMapping("/selectById")
    public Result selectById(@RequestParam Long id) {
        User user = userService.selectById(id);
        return Result.success(user);
    }

    @GetMapping("/sqlInject/test")
    public Result selectByUserNameSqlInject(@RequestParam("userName") String userName) {
        List<User> page = userService.selectByUserNameSqlInject(userName);
        return Result.success(page);
    }

    /**
     * 通过拼接sql字段的方式返回结果
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageSpliceSql")
    public Result selectUserPageSpliceSql(@RequestBody UserQueryVo user) {
        IPage<Map> page = userService.selectUserPageSpliceSql(user);
        return Result.success(page);
    }

    /**
     * 通过json序列化返回需要的字段
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageWithJsonSerialized")
    public Result selectUserPageWithJsonSerialized(@RequestBody UserQueryVo user) {
        IPage<Map> page = userService.selectUserPageWithJsonSerialized(user);
        return Result.success(page);
    }

    /**
     * 自定义工具类实现
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageUseCustom")
    public Result selectUserPageUseCustom(@RequestBody UserQueryVo user) {
        IPage<Map> page = userService.selectUserPageUseCustom(user);
        return Result.success(page);
    }

    @PostMapping("/export")
    public void export(@RequestBody UserQueryVo user) {
        userService.export(user);
    }

    /**
     * 使用注解FieldAuth2修改分页的返回值
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageWithAnnotation")
    public Result selectUserPageWithAnnotation(@RequestBody UserQueryVo user) {
        IPage<User> page = userService.selectUserPageWithAnnotation(user);
        return Result.success(page);
    }

    /**
     * 使用注解FieldAuth修复列表的返回值
     * @param user
     * @return
     */
    @PostMapping("/selectUserListWithAnnotation")
    public Result selectUserListWithAnnotation(@RequestBody UserQueryVo user) {
        List<Map> list = userService.selectUserListWithAnnotation(user);
        return Result.success(list);
    }


    /**
     * 通过mybatis的插件修改查询的字段
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageWithModifyColumn")
    public Result selectUserPageWithModifyColumn(@RequestBody UserQueryVo user) {
        IPage<User> page = userService.selectUserPageWithModifyColumn(user);
        return Result.success(page);
    }

    /**
     * 通过mybatis的插件修改返回结果集字段
     * @param user
     * @return
     */
    @PostMapping("/selectUserPageWithModifyResultSet")
    public Result selectUserPageWithModifyResultSet(@RequestBody UserQueryVo user) {
        IPage<User> page = userService.selectUserPageWithModifyResultSet(user);
        return Result.success(page);
    }
}
